package com.fanben100.gui.i18n;

import java.util.LinkedList;
import java.util.Locale;
import java.util.ResourceBundle;

import com.fanben100.util.StringUtil;

/**
 * 资源管理类
 * 
 * @author Administrator
 * 
 */
public class ResourceContext {

	private LinkedList<LangChangeListener> listeners = new LinkedList<LangChangeListener>();
	private ResourceBundle bundle;
	private Locale locale;
	private boolean changed = false;

	// ResourceBundle file
	private static final String RESOURCE_NAME = "resources.fbpos";

	private static String prefix = null;

	private static class ResourceManagerSingleHolder {
		private static ResourceContext resourcecontext = new ResourceContext();
	}

	public static ResourceContext getInstance(String... pref) {
		if (pref != null && pref.length > 0) {
			prefix = pref[0];
		}
		return ResourceManagerSingleHolder.resourcecontext;
	}

	public void changeLocal(Locale newLocal) {
		if (newLocal != null) {
			locale = newLocal;
			changed = true;
		}
	}

	// get value by key
	@SuppressWarnings("finally")
	public String getString(String key) {
		String value = "";
		// try {
		value = getBundle().getString(
				(prefix != null ? prefix + "." : "") + key);
		// } catch (MissingResourceException e) {
		// value = key;
		// throw e;
		// } finally {
		return value;
		// }
	}

	@SuppressWarnings("finally")
	public String getString(String key, String pref) {
		String value = "";
		value = getBundle().getString(pref + "." + key);
		return value;
	}

	@SuppressWarnings("finally")
	public String getColonString(String key) {
		String value = "";
		value = getBundle().getString(
				(prefix != null ? prefix + "." : "") + key)
				+ ":";
		return value;
	}

	/**
	 * get bundle
	 * 
	 * @return
	 */
	private ResourceBundle getBundle() {
		if (locale == null) {
			locale = new Locale("zh", "CN");
			changed = true;
		}
		if (bundle == null) {
			bundle = ResourceBundle.getBundle(RESOURCE_NAME, locale);
		} else {
			if (changed) {
				bundle = ResourceBundle.getBundle(RESOURCE_NAME, locale);
				changed = false;
			}
		}
		return bundle;
	}

	public void addListener(LangChangeListener lsn) {
		listeners.add(lsn);
	}

	// Invoke listener
	public void languageChangedEvent(Locale locale) {
		changeLocal(locale);
		for (LangChangeListener listener : listeners) {
			if (listener != null) {
				listener.updateResource();
			}
		}
	}

}